package gui.components;

import gfx.layers.LayerManager;
import gui.components.renderers.LayerListCell;
import gui.components.renderers.LayerListCellRenderer;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class LayerList extends JPanel implements ListDataListener{
	
  private static final long serialVersionUID = 1L;
	private JScrollPane scrollPane;
	private JPanel contentPanel;
	private LayerListCellRenderer cellRenderer;
	private LayerManager layerManager;
	
	public LayerList(LayerManager layerManager){
		super(new BorderLayout(5, 5));
		this.layerManager = layerManager;
		layerManager.addListDataListener(this);
		
		initialize();
	}
	
	private void initialize(){
		scrollPane = new JScrollPane();
		contentPanel = new JPanel();
		cellRenderer = new LayerListCellRenderer();
		
		scrollPane.setViewportView(contentPanel);
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setPreferredSize(new Dimension(10, 300));
		scrollPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
		
		contentPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
		renderAllLayers();
		
		add(scrollPane, BorderLayout.CENTER);
	}
	
	private void renderAllLayers(){
		for(int i = 0; i < layerManager.getSize(); i++){
			Component layerCell = cellRenderer.getListCellRendererComponent(layerManager.getElementAt(i));
			contentPanel.add(layerCell);
			contentPanel.setPreferredSize(new Dimension(scrollPane.getWidth(), layerManager.getSize() * LayerListCell.LIST_ENTRY_HEIGHT));
		}
	}

	@Override
  public void intervalAdded(ListDataEvent e) {
	  for(int i = e.getIndex0(); i < e.getIndex1(); i++){
	  	Component layerCell = cellRenderer.getListCellRendererComponent(layerManager.getElementAt(i));
			contentPanel.add(layerCell, i);
			contentPanel.setPreferredSize(new Dimension(scrollPane.getWidth(), layerManager.getSize() * LayerListCell.LIST_ENTRY_HEIGHT));
	  }
	  contentPanel.revalidate();
  }

	@Override
  public void intervalRemoved(ListDataEvent e) {
		for(int i = e.getIndex0(); i < e.getIndex1(); i++){
			contentPanel.remove(e.getIndex0());
			contentPanel.setPreferredSize(new Dimension(scrollPane.getWidth(), layerManager.getSize() * LayerListCell.LIST_ENTRY_HEIGHT));
	  }
		contentPanel.revalidate();
  }

	@Override
  public void contentsChanged(ListDataEvent e) {
		intervalRemoved(e);
		intervalAdded(e);
  }
	
	public int getListEntryWidth(){
		return scrollPane.getViewport().getWidth() - scrollPane.getVerticalScrollBar().getWidth();
	}
}
